import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as Img;
import 'package:path_provider/path_provider.dart';
import 'package:smart_translator/app/modules/photoTranslate/views/gallery.dart';
import '../../../utils/tips.dart';
import './detailDialog.dart';
import './shareDialog.dart';
import '../controllers/utilsFile.dart';

class BlurImage extends StatefulWidget {
  BlurImage({
    Key? key,
    required this.path,
    required this.result,
    required this.screenWidth,
    required this.currentSrc,
    required this.currentTgt,
    required this.srcLang,
    required this.tgtLang,
    required this.translateVoice,
    required this.changePageState,
    required this.addPhoto,
    required this.clickDelete,
    required this.galleryData,
  }) : super(key: key);
  final String path;
  final result;
  final screenWidth;
  final currentSrc;
  final currentTgt;
  final srcLang;
  final tgtLang;
  final translateVoice;
  final changePageState;
  final addPhoto;
  final clickDelete;
  final galleryData;
  @override
  State<BlurImage> createState() => _BlurImageState();
}

class _BlurImageState extends State<BlurImage> {
  late ui.Image fillImage;
  bool isImageLoaded = false;
  bool isHide = false;
  bool isSave = false;
  bool isGallery = false;
  late int picWidth;
  late int picHeight;
  late File firstImage;
  int galleryIndex = 0;

  var selectPicArr = [];

  void initState() {
    super.initState();
    init();
  }

  static GlobalKey repaintBoundaryKey = GlobalKey(); // 创建GlobalKey

  Future<void> init() async {
    final Uint8List data = await File(widget.path).readAsBytes();
    fillImage = await loadImage(data, widget.screenWidth);
    Future.delayed(Duration(milliseconds: 200), () {
      saveImage(false);
    });
    // if(widget.galleryData[0]){
    //   var getFirstImage = await File(widget.galleryData[0]['tgt']);
    //   print('getFirstImage${getFirstImage}');
    //   setState(() {
    //     firstImage = getFirstImage;
    //   });
    // }
  }

  Future<ui.Image> loadImage(Uint8List img, screenWidth) async {
    final oriimg = Img.decodeImage(img);
    picWidth = screenWidth.toInt() - 0;
    var imageWidth = oriimg?.width as int;
    var imageHeight = oriimg?.height as int;
    picHeight = (picWidth * (imageHeight / imageWidth)).toInt();

    final Completer<ui.Image> completer = Completer();
    ui.decodeImageFromList(img, (ui.Image img) {
      setState(() {
        isImageLoaded = true;
      });
      return completer.complete(img);
    });
    return completer.future;
  }

  findTextByPosition(offset, picResult) {
    var currentSrc = widget.currentSrc;
    var currentTgt = widget.currentTgt;
    var srcLang = widget.srcLang;
    var tgtLang = widget.tgtLang;
    filterCondition(dx, dy, spanItem) {
      var bounding = spanItem['bounding'];
      var topLeftPoint = bounding[0];
      var topRightPoint = bounding[1];
      var bottomRightPoint = bounding[2];
      var bottomLeftPoint = bounding[3];
      return (topLeftPoint['x'].toDouble() <= dx) &&
          (bottomLeftPoint['x'].toDouble() <= dx) &&
          (topRightPoint['x'].toDouble() >= dx) &&
          (bottomRightPoint['x'].toDouble() >= dx) &&
          (topLeftPoint['y'].toDouble() <= dy) &&
          (topRightPoint['y'].toDouble() <= dy) &&
          (bottomLeftPoint['y'].toDouble() >= dy) &&
          (bottomRightPoint['y'].toDouble() >= dy);
    }

    var filterRes = List.from(
      picResult,
    ).where((item) => filterCondition(offset.dx, offset.dy, item));
    if (!filterRes.isEmpty) {
      // 清除可能存在的音频文件
      PhotoUtil.clearVoiceFile();
      showDialog(
        context: context,
        barrierColor: Color(0xFFF3F2F8),
        builder: (BuildContext context) {
          return DialogView(
            srcCode: currentSrc,
            tgtCode: currentTgt,
            srcText: filterRes.first['text'],
            tgtText: filterRes.first['translation'],
            srcLang: srcLang,
            tgtLang: tgtLang,
            translateVoice: widget.translateVoice,
          );
        },
      );
    }
  }

  void switchHideIcon() {
    setState(() {
      isHide = !isHide;
    });
  }

  Future<void> saveImage(isShare) async {
    if (isSave) {
      return;
    }
    final boundary =
        repaintBoundaryKey.currentContext?.findRenderObject()
            as RenderRepaintBoundary;
    final image = await boundary.toImage(); // 捕获图像到内存中
    final byteData = await image.toByteData(
      format: ui.ImageByteFormat.png,
    ); // 将图像转换为字节数据
    final pngBytes = byteData?.buffer.asUint8List();
    print('pngBytes${pngBytes}');
    if (pngBytes != null) {
      final directory =
          '${(await getTemporaryDirectory()).path}/photoTranslateDir';
      final timeStamp = DateTime.now().millisecondsSinceEpoch;
      final file = File('${directory}/${timeStamp}.png'); // 创建文件路径
      await file.writeAsBytes(pngBytes); // 将字节数据写入文件
      print('widget.result${widget.result}');
      final resultText =
          widget.result.map((item) => item['translation']).toList();
      widget.addPhoto({
        'tgt': '${directory}/${timeStamp}.png',
        'height': picWidth.toDouble(),
        'width': picHeight.toDouble(),
        'resultText': resultText,
      });
      setState(() {
        isSave = true;
      });
      if (isShare) {
        // 先清空已选数据
        selectPicArr = [];
        showDialog(
          context: context,
          barrierColor: Color(0xFFF3F2F8),
          builder: (BuildContext context) {
            return ShareDialog(
              galleryData: widget.galleryData,
              changePickPicState: changePickPicState,
              share: share,
            );
          },
        );
      }
    } else {
      print('Failed to convert image to bytes.'); // 如果转换失败，打印错误信息
    }
  }

  // 记录分享页面选择图片
  changePickPicState(selectList) {
    setState(() {
      selectPicArr = selectList;
    });
  }

  share(type) {
    //  分享功能
    if (selectPicArr.length == 0) {
      Tips.showToast('请选择图片！');
      return;
    }
    if (type == 'pic') {
      PhotoUtil.sharePic(selectPicArr);
      return;
    }
    if (type == 'text') {
      PhotoUtil.shareText(selectPicArr);
      return;
    }
    if (type == 'album') {
      PhotoUtil.saveToAlbum(selectPicArr);
    }
  }
  
  void setIndex(int index){
    galleryIndex = index;
  }

  @override
  Widget build(BuildContext context) {
    if (this.isImageLoaded) {
      return Stack(
        children: [
          Visibility(
            visible: (!isGallery)&&(!isHide),
            child: GestureDetector(
              onTapDown: (TapDownDetails details) {
                // 获取点击位置
                final position = details.localPosition;
                findTextByPosition(position, widget.result);
              },
              child: RepaintBoundary(
                key: repaintBoundaryKey, // 将key分配给RepaintBoundary
                child: CustomPaint(
                  painter: BlurImagePainter(
                    bgImage: fillImage,
                    picResult: widget.result,
                    saveImage: saveImage,
                  ),
                  child: Container(
                    width: picWidth.toDouble(),
                    height: picHeight.toDouble(),
                    // width:400,
                    // height: 400,
                  ),
                ),
              ),
            ),
          ),
          Visibility(
            visible: (!isGallery) &&isHide,
            child: CustomPaint(
              painter: PureImagePainter(bgImage: fillImage),
              child: Container(
                width: picWidth.toDouble(),
                height: picHeight.toDouble(),
              ),
            ),
          ),
          Visibility(
            visible: isGallery,
              child:Gallery(galleryData: widget.galleryData, changePickPicState: changePickPicState,isPureReview:true,setIndex:setIndex)
          ),
          Positioned(
            child: Container(
              color: Colors.grey[700],
              height: 76,
              child: Padding(
                padding: EdgeInsets.only(left: 44.0, right: 44.0),
                child: Row(
                  children: [
                    InkWell(
                      onTap: () {
                        saveImage(false);
                        widget.changePageState('pickFromCamera');
                      },
                      child: Container(
                        width: 32,
                        height: 32,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle, // 设置为圆形
                          color: Colors.black, // 设置背景颜色
                        ),
                        child: Image.asset(
                          'assets/images/icon_add_photo.png',
                          width: 16.0,
                          height: 16.0,
                        ),
                      ),
                    ),

                    Spacer(),
                    Visibility(
                      // visible: false,
                      visible: widget.galleryData.length>0,
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            isGallery = !isGallery;
                          });
                        },
                        child:
                            widget.galleryData.length > 0
                                ? Image.file(
                                  File(widget.galleryData[0]['tgt']),
                                  width: 32,
                                  height: 32,
                                )
                                : Spacer(),
                      ),
                    ),
                    Visibility(
                      // visible: false,
                      visible: widget.galleryData.length>0,
                      child: Spacer(),
                    ),
                    InkWell(
                      onTap: () {
                        widget.clickDelete(isGallery,galleryIndex);
                        // widget.changePageState('pickFromCamera');
                      },
                      child: Container(
                        width: 48,
                        height: 48,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle, // 设置为圆形
                          color: Colors.black, // 设置背景颜色
                        ),
                        child: Image.asset(
                          'assets/images/icon_delete_photo.png',
                          width: 16.0,
                          height: 16.0,
                        ),
                      ),
                    ),

                    Spacer(),
                    InkWell(
                      onTap: () {
                        if (isSave) {
                          selectPicArr = [];
                          showDialog(
                            context: context,
                            barrierColor: Color(0xFFF3F2F8),
                            builder: (BuildContext context) {
                              return ShareDialog(
                                galleryData: widget.galleryData,
                                changePickPicState: changePickPicState,
                                share: share,
                              );
                            },
                          );
                        }
                        // saveImage(true);
                      },
                      child: Container(
                        width: 48,
                        height: 48,
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            Container(
                              width: 32,
                              height: 32,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle, // 设置为圆形
                                color: Colors.black, // 设置背景颜色
                              ),
                              child: Center(
                                child: Image.asset(
                                  'assets/images/icon_share_photo.png',
                                  width: 16.0,
                                  height: 16.0,
                                ),
                              ),
                            ),
                            Positioned(
                              top: 0,
                              right: 0,
                              child: Container(
                                width: 20,
                                height: 20,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Color(0xFF0D65E6),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      '${isSave ? widget.galleryData.length : widget.galleryData.length + 1}',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12,
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            bottom: 0,
            left: 0,
            width: picWidth.toDouble(),
          ),
          if(!isGallery)
          Positioned(
            child: InkWell(
              onTap: () {
                switchHideIcon();
              },
              child: Image.asset(
                isHide
                    ? 'assets/images/icon_hide_text.png'
                    : 'assets/images/icon_show_text.png',
              ),
            ),

            right: 10,
            top: 5,
            width: 32,
            height: 32,
          ),
        ],
      );
    } else {
      return Text('Loading......');
      // return CircularProgressIndicator();
    }
  }
}

class BlurImagePainter extends CustomPainter {
  final ui.Image bgImage;
  final picResult;
  final saveImage;
  BlurImagePainter({
    required this.bgImage,
    required this.picResult,
    required this.saveImage,
  });
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = Colors.white; // 设置画笔颜色
    paint.strokeCap = StrokeCap.round;

    canvas.drawImageRect(
      bgImage,
      Rect.fromLTRB(0, 0, bgImage.width.toDouble(), bgImage.height.toDouble()),
      Offset.zero & size,
      paint,
    );

    // 绘制文本
    for (var textSpan in picResult) {
      // 后端返回的位置数据是左上角顺时针
      var bounding = textSpan['bounding'];
      var topLeftPoint = bounding[0];
      var topRightPoint = bounding[1];
      var bottomRightPoint = bounding[2];
      var bottomLeftPoint = bounding[3];

      Path path =
          Path()..moveTo(
            topLeftPoint['x'].toDouble(),
            topLeftPoint['y'].toDouble(),
          );
      path.lineTo(topRightPoint['x'].toDouble(), topRightPoint['y'].toDouble());
      path.lineTo(
        bottomRightPoint['x'].toDouble(),
        bottomRightPoint['y'].toDouble(),
      );
      path.lineTo(
        bottomLeftPoint['x'].toDouble(),
        bottomLeftPoint['y'].toDouble(),
      );
      path.close();
      canvas.drawPath(path, paint);
      final widthLength = (topRightPoint['x'] - topLeftPoint['x']).abs() * 1.5;
      final heightLength = (bottomLeftPoint['y'] - topLeftPoint['y']).abs();
      bool isCol = heightLength > widthLength; //判断是否为竖向排列
      final fontsize =
          isCol
              ? ((topRightPoint['x'] - topLeftPoint['x']).abs()).floor()
              : (bottomLeftPoint['y'] - topLeftPoint['y']).abs().floor();
      final actualFontsize = fontsize > 12 ? 12 : fontsize;
      TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: textSpan["translation"],
          style: TextStyle(
            color: Colors.black,
            fontSize: actualFontsize.toDouble(),
          ),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout(maxWidth: 100); // 布局文本
      textPainter.paint(
        canvas,
        Offset(topLeftPoint['x'].toDouble(), topLeftPoint['y'].toDouble()),
      ); // 在指定位置绘制文本
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

class PureImagePainter extends CustomPainter {
  final ui.Image bgImage;
  PureImagePainter({required this.bgImage});
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = Colors.white;

    canvas.drawImageRect(
      bgImage,
      Rect.fromLTRB(0, 0, bgImage.width.toDouble(), bgImage.height.toDouble()),
      Offset.zero & size,
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
